package top.dancun.easuser.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.dancun.common.exception.RRException;
import top.dancun.common.utils.DateUtils;
import top.dancun.easuser.dao.CaptchaDao;
import top.dancun.easuser.entity.CaptchaEntity;
import top.dancun.easuser.service.CaptchaService;

import java.awt.image.BufferedImage;
import java.util.Date;


@Service("captchaService")
public class CaptchaServiceImpl extends ServiceImpl<CaptchaDao, CaptchaEntity> implements CaptchaService {
    @Autowired
    private Producer producer ;

    @Override
    public boolean validate(String uuid, String captcha) {
        CaptchaEntity captchaEntity = this.lambdaQuery().eq(CaptchaEntity::getUuid,uuid).one();
        if (captchaEntity==null){
            return false;
        }

        System.out.println(captchaEntity.getExpireTime().getTime()>=System.currentTimeMillis());
        if (captcha!=null && captcha.equalsIgnoreCase(captchaEntity.getCode()) && captchaEntity.getExpireTime().getTime()>=System.currentTimeMillis()){
            this.removeById(uuid);
            return true;
        }
        return false;
    }

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if(StringUtils.isBlank(uuid)){
            throw new RRException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        CaptchaEntity captchaEntity = new CaptchaEntity();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
        this.save(captchaEntity);

        return producer.createImage(code);
    }

}